﻿using AutoMapper;
using Harmontronics.IService;
using Harmontronics.Model.Dto.Menu;
using Harmontronics.Model.Dto.Role;
using Harmontronics.Model.Entitys;
using Harmontronics.Model.Other;
using Harmontronics.Repository;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Harmontronics.Service
{
    public class RoleService : IRoleService
    {
        private readonly IMapper _mapper;
        private HcDbContext _db { get; set; }

        public RoleService(IMapper mapper, HcDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }

        public List<string> GetRoleDiscListByUserId(long id)
        {
            List<UserRoleRelation> info = _db.UserRoleRelation.Where(x => x.UserId == id).ToList();
            List<string> descriptions = new List<string>();
            foreach (var rela in info)
            {
                Role role = _db.Roles.FirstOrDefault(x => x.Id == rela.RoleId);
                if (role != null)
                {
                    descriptions.Add(role.RoleName);
                }
            }
            return descriptions;
        }
        public List<RoleReq> GetAllRoles()
        {
            List<RoleReq> roleList = new List<RoleReq>();
            List<Role> roles = _db.Roles.ToList();
            foreach (var role in roles)
            {
                RoleReq rolereq = _mapper.Map<RoleReq>(role);
                roleList.Add(rolereq);
            }
            return roleList.OrderBy(i => i.RoleSort).ToList();
        }

        public List<RoleReq> GetAliveRoles()
        {
            List<RoleReq> roleList = new List<RoleReq>();
            List<Role> roles = _db.Roles.Where(i => i.Enable == 1).ToList();
            foreach (var role in roles)
            {
                RoleReq rolereq = _mapper.Map<RoleReq>(role);
                roleList.Add(rolereq);
            }
            return roleList.OrderBy(i => i.RoleSort).ToList();
        }
        UserRoleRelation IRoleService.GetRelationByUserId(int id)
        {
            UserRoleRelation role = _db.UserRoleRelation.SingleOrDefault(x => x.UserId == id);
            return _mapper.Map<UserRoleRelation>(role);
        }

        RoleRes IRoleService.GetRoleById(int id)
        {
            Role role = _db.Roles.SingleOrDefault(x => x.Id == id);
            return _mapper.Map<RoleRes>(role);
        }

        bool IRoleService.Add(RoleAdd roleAdd)
        {
            Role role = _mapper.Map<Role>(roleAdd);
            role.CreateTime = DateTime.Now;
            try
            {
                _db.Roles.Add(role);
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        bool IRoleService.UpdateRole(RoleEdit roleEdit)
        {
            try
            {
                Role role = _db.Roles.SingleOrDefault(x => x.Id == roleEdit.Id);
                _mapper.Map(roleEdit, role);
                role.UpdateTime = DateTime.Now;
                _db.Roles.Update(role);
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        bool IRoleService.Del(int id)
        {
            try
            {
                Role role = _db.Roles.Where(i => i.Id == id).FirstOrDefault();
                List<MenuRoleRelation> mrelation = _db.MenuRoleRelation.Where(i => i.RoleId == id).ToList();
                List<UserRoleRelation> urelation = _db.UserRoleRelation.Where(i => i.RoleId == id).ToList();
                //删除role
                if (role != null)
                {
                    _db.Roles?.Remove(role);
                    _db.MenuRoleRelation.RemoveRange(mrelation);
                    _db.UserRoleRelation.RemoveRange(urelation);
                    _db.SaveChanges();
                }
                //删除rolemenu
            }
            catch (Exception e)
            {
                return false;
            }
            return true;

        }

        public bool BatchDel(List<int> ids)
        {
            try
            {
                List<Role> entities = _db.Roles.Where(i => ids.Contains(i.Id)).ToList();
                List<MenuRoleRelation> menuRoleRelations = _db.MenuRoleRelation.Where(i => ids.Contains((int)i.RoleId)).ToList();
                List<UserRoleRelation> userRoleRelations = _db.UserRoleRelation.Where(i => ids.Contains(i.RoleId)).ToList();

                if (entities.Count > 0)
                {
                    _db.Roles.RemoveRange(entities);
                    _db.MenuRoleRelation.RemoveRange(menuRoleRelations);
                    _db.UserRoleRelation.RemoveRange(userRoleRelations);
                    _db.SaveChanges();
                }
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public bool UpdateRoleMenus(UpdateRoleMenuInput input)
        {
            try
            { //检查是否重复
                List<MenuRoleRelation> relation = _db.MenuRoleRelation.Where(i => i.RoleId == input.roleId).ToList();

                _db.MenuRoleRelation.RemoveRange(relation);
                foreach (var menuId in input.menuIds)
                {

                    _db.MenuRoleRelation.Add(new MenuRoleRelation
                    {
                        MenuId = menuId,
                        RoleId = input.roleId
                    });
                }
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public bool UpdateRoleEnable(UpdateRoleEnable update)
        {
            try
            {
                Role role = _db.Roles.SingleOrDefault(i => i.Id == update.id);
                if (role != null)
                {
                    role.Enable = update.enable;
                    _db.Roles?.Update(role);
                    _db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public bool UpdateUserRole(int userId, string roleName)
        {
            try
            {
                Role role = _db.Roles.Where(i => i.RoleName == roleName).FirstOrDefault();
                List<UserRoleRelation> relationList = _db.UserRoleRelation.Where(i => i.UserId == userId).ToList();
                _db.UserRoleRelation.RemoveRange(relationList);
                if (role != null)
                {
                    _db.Add(new UserRoleRelation
                    {
                        RoleId = role.Id,
                        UserId = userId
                    });
                    _db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        public bool UpdateUserRole(string employeeNumber, string roleName)
        {
            throw new NotImplementedException();
        }

        public bool UpdateUserRole(int userId, int? roleId)
        {
            try
            {
                if (roleId != null)
                {
                    List<UserRoleRelation> relationList = _db.UserRoleRelation.Where(i => i.UserId == userId).ToList();
                    _db.UserRoleRelation.RemoveRange(relationList);
                    _db.Add(new UserRoleRelation
                    {
                        RoleId = (int)roleId,
                        UserId = userId
                    });
                    _db.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
    }
}
